using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.suppliers;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.suppliers
{
    /// <summary>
    /// 批量逻辑删除供应商命令处理器
    /// </summary>
    public class BatchDeleteSuppliersCommandHandler : IRequestHandler<BatchDeleteSuppliersCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Supplier> _supplierRepository;
        private readonly ILogger<BatchDeleteSuppliersCommandHandler> _logger;

        public BatchDeleteSuppliersCommandHandler(
            IBaseRepository<Supplier> supplierRepository,
            ILogger<BatchDeleteSuppliersCommandHandler> logger)
        {
            _supplierRepository = supplierRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理批量逻辑删除供应商命令
        /// </summary>
        /// <param name="request">批量删除供应商命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<int>> Handle(BatchDeleteSuppliersCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始批量逻辑删除供应商，ID数量: {Count}, IDs: {Ids}", 
                    request.Ids.Count, string.Join(",", request.Ids));

                // 获取所有需要删除的供应商（排除已删除的）
                var suppliersToDelete = await _supplierRepository.GetAll()
                    .Where(s => request.Ids.Contains(s.Id) && !s.IsDeleted)
                    .ToListAsync(cancellationToken);

                if (!suppliersToDelete.Any())
                {
                    _logger.LogWarning("没有找到需要删除的供应商，IDs: {Ids}", string.Join(",", request.Ids));
                    return ApiResult<int>.Error("没有找到需要删除的供应商");
                }

                // 检查是否有启用状态的供应商
                var enabledSuppliers = suppliersToDelete.Where(s => s.Status == "启用").ToList();
                if (enabledSuppliers.Any())
                {
                    var enabledNames = string.Join(",", enabledSuppliers.Select(s => s.SupplierName));
                    _logger.LogWarning("批量删除中包含启用状态的供应商，无法删除: {Names}", enabledNames);
                    return ApiResult<int>.Error($"以下供应商为启用状态，无法删除：{enabledNames}，请先停用后再删除");
                }

                // 执行批量逻辑删除
                foreach (var supplier in suppliersToDelete)
                {
                    supplier.IsDeleted = true;
                    supplier.UpdatedTime = DateTime.Now;
                    supplier.UpdatedBy = 1;
                }

                // 执行批量更新操作
                var result = await _supplierRepository.UpdateRanger(suppliersToDelete);

                if (result > 0)
                {
                    var deletedNames = string.Join(",", suppliersToDelete.Select(s => s.SupplierName));
                    _logger.LogInformation("成功批量逻辑删除供应商，删除数量: {Count}, 供应商名称: {Names}", 
                        result, deletedNames);
                    
                    return ApiResult<int>.Success(result, $"成功删除 {result} 个供应商");
                }
                else
                {
                    _logger.LogError("批量逻辑删除供应商失败，IDs: {Ids}", string.Join(",", request.Ids));
                    
                    return ApiResult<int>.Error("批量删除供应商失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量逻辑删除供应商时发生异常，IDs: {Ids}", string.Join(",", request.Ids));
                
                return ApiResult<int>.Error($"批量删除供应商时发生异常: {ex.Message}");
            }
        }
    }
} 